package com.orhon.smartcampus.modules.systemctl.fetcher;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.orhon.smartcampus.auth.JwtUtils;
import com.orhon.smartcampus.basicComponents.Result;
import com.orhon.smartcampus.modules.base.dao.GradesDao;
import com.orhon.smartcampus.modules.base.dao.PeriodsDao;
import com.orhon.smartcampus.modules.base.dao.SubjectsDao;
import com.orhon.smartcampus.modules.base.entity.Grades;
import com.orhon.smartcampus.modules.base.entity.Periods;
import com.orhon.smartcampus.modules.base.entity.Schools;
import com.orhon.smartcampus.modules.base.entity.Subjects;
import com.orhon.smartcampus.modules.base.gqlModel.GQLGrades;
import com.orhon.smartcampus.modules.base.gqlModel.GQLPageParam;
import com.orhon.smartcampus.modules.base.gqlModel.GQLPeriod;
import com.orhon.smartcampus.modules.base.gqlModel.GQLSchool;
import com.orhon.smartcampus.modules.base.gqlModel.GQLSubject;
import com.orhon.smartcampus.modules.base.mm.EnvArgsMapper;
import com.orhon.smartcampus.modules.base.mm.GradeMapper;
import com.orhon.smartcampus.modules.base.mm.PeriodMapper;
import com.orhon.smartcampus.modules.base.mm.SchoolMapper;
import com.orhon.smartcampus.modules.base.mm.SubjectMapper;
import com.orhon.smartcampus.modules.course.dao.CoursesDao;
import com.orhon.smartcampus.modules.course.entity.Courses;
import com.orhon.smartcampus.modules.course.gqlModel.GQLCourses;
import com.orhon.smartcampus.modules.course.mm.CoursesMapper;
import com.orhon.smartcampus.modules.systemctl.dao.OrgDutiesDao;
import com.orhon.smartcampus.modules.systemctl.dao.SchoolSettingsDao;
import com.orhon.smartcampus.modules.systemctl.entity.OrgDuties;
import com.orhon.smartcampus.modules.systemctl.entity.Schoolsettings;
import com.orhon.smartcampus.modules.systemctl.gqlModel.GQLDuty;
import com.orhon.smartcampus.modules.systemctl.gqlModel.GQLSchoolSettings;
import com.orhon.smartcampus.modules.systemctl.mm.DutiesMapper;
import com.orhon.smartcampus.modules.systemctl.mm.SchoolSettingsMapper;
import com.orhon.smartcampus.modules.user.dao.TokenService;
import com.orhon.smartcampus.utils.ObjectToMap;
import com.orhon.smartcampus.utils.R;
import com.orhon.smartcampus.utils.Util;

import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;

@Component
public class SchoolsettingsFetcher implements DataFetcher {


    @Autowired
    SchoolSettingsDao schoolSettingsDao;

    @Autowired
    TokenService tokenService;

    @Autowired
    GradesDao gradesDao;

    @Autowired
    PeriodsDao periodsDao;

    @Autowired
    SubjectsDao subjectsDao;

    @Autowired
    OrgDutiesDao orgDutiesDao;

    @Autowired
    CoursesDao coursesDao;

    /**
     * 获取学校设置列表
     *
     * @param environment
     * @return
     * @throws Exception editor : ths
     */
    @Override
    public Object get(DataFetchingEnvironment environment) throws Exception {

        List<GQLSchoolSettings> gqlSchoolSettings = new ArrayList<>();

        String token = tokenService.getSystemToken();
        if(token==null) {
            return  R.NoLogin();
        }
        Long schoolId = JwtUtils.getSchoolId(token);
        GQLPageParam page = EnvArgsMapper.MAPPER.fromArgs(environment);
        String hql = "from Schoolsettings where deleted_at = null ";
        if(environment.containsArgument("condition")) {
            HashMap<String,Object> map = ObjectToMap.to(environment.getArgument("condition"));
            if(map.get("id")!=null) {
            	hql += "and id " + Util.decide(map.get("id"));
            }
            if(map.get("school_id")!=null) {
                hql += "and school_id " + Util.decide(map.get("school_id"));
            }
        }
        
        
        List<Schoolsettings> list = schoolSettingsDao.find(hql, null, page.getPage(), page.getLimit());


        for (Schoolsettings item : list) {
            GQLSchool gqlSchools = null;
            if (environment.getSelectionSet().contains("data/school")){
                Schools school = item.getBaseSchoolsBySchoolId();
                gqlSchools = SchoolMapper.MAPPER.toSchool(school);
            }

            List<GQLGrades> gqlGrades = null;
            if (environment.getSelectionSet().contains("data/grades")){
                String gradesString = item.getGrades().replace("[","").replace("]","").replace(" ", "");
                if(gradesString.length() > 0){
                    String[] gradesArray = gradesString.split(",");
                    //将String数组转成Integer数组
                    Integer[] integerArray = (Integer[]) ConvertUtils.convert(gradesArray, Integer.class);
                    StringBuilder ids = new StringBuilder();
                	ids.append("(");
                	for(Integer integer:integerArray){
                		 ids.append(integer);
                		 ids.append(",");
    				}
                	ids.delete(ids.length()-1 , ids.length());
                	ids.append(")");
    				String hql1 = "from Grades where deleted_at = null and id in "+ ids.toString() + " ";
    				List<Grades> find = gradesDao.find(hql1);
    				gqlGrades = GradeMapper.MAPPER.toGradeList(find);
//    				for(Integer integer:integerArray){
//                        String gradesHql = "from Grades where deleted_at = null and id = " + integer;
//                        Grades grades = gradesDao.findId(gradesHql, null);
//                        GQLGrades gqlGrade = GradeMapper.MAPPER.toGrade(grades);
//                        gqlGrades.add(gqlGrade);
//                    }
                }
            }

            List<GQLPeriod> gqlPeriods = new ArrayList<>();
            if (environment.getSelectionSet().contains("data/periods")){
                String periodsString = item.getPeriods().replace("[","").replace("]","").replace(" ", "");
                if(periodsString.length() > 0){
                    String[] periodsArray = periodsString.split(",");
                    //将String数组转成Integer数组
                    Integer[] integerArray = (Integer[]) ConvertUtils.convert(periodsArray, Integer.class);
                    for(Integer integer:integerArray){
                        String subjectsHql = "from Periods where deleted_at = null and id = " + integer;
                        Periods periods = periodsDao.findId(subjectsHql, null);
                        GQLPeriod gqlPeriod = PeriodMapper.MAPPER.toPeriods(periods);
                        gqlPeriods.add(gqlPeriod);
                    }
                }
            }

            List<GQLSubject> gqlSubjects = new ArrayList<GQLSubject>();
            if (environment.getSelectionSet().contains("data/subjects")){
                String subjectsString = item.getSubjects().replace("[","").replace("]","").replace(" ", "");
                if(subjectsString.length() > 0){
                    String[] subjectsArray = subjectsString.split(",");
                    //将String数组转成Integer数组
                    Integer[] integerArray = (Integer[]) ConvertUtils.convert(subjectsArray, Integer.class);
                    for(Integer integer:integerArray){
                        String subjectsHql = "from Subjects where deleted_at = null and id = " + integer;
                        Subjects subjects = subjectsDao.findId(subjectsHql, null);
                        GQLSubject gqlSubject = SubjectMapper.MAPPER.toSubject(subjects);
                        gqlSubjects.add(gqlSubject);
                    }
                }
            }
            List<GQLCourses> gqlCoursess = new ArrayList<>();
            if (environment.getSelectionSet().contains("data/courses")){
                String coursesString = item.getCourses().replace("[","").replace("]","").replace(" ", "");
                if(coursesString.length() > 0){
                    String[] coursesArray = coursesString.split(",");
                    //将String数组转成Integer数组
                    Integer[] integerArray = (Integer[]) ConvertUtils.convert(coursesArray, Integer.class);
                    for(Integer integer:integerArray){
                        String subjectsHql = "from Courses where deleted_at = null and id = " + integer;
                        Courses courses = coursesDao.findId(subjectsHql, null);
                        GQLCourses gqlCourses = CoursesMapper.MAPPER.toCourses(courses);
                        gqlCoursess.add(gqlCourses);
                    }
                }
            }
            List<GQLDuty> gqlDutys = new ArrayList<GQLDuty>();
            if (environment.getSelectionSet().contains("data/duties")){
                String orgDutiesString = item.getDuties().replace("[","").replace("]","").replace(" ", "");
                if(orgDutiesString.length() > 0){
                    String[] orgDutiesArray = orgDutiesString.split(",");
                    //将String数组转成Integer数组
                    Integer[] integerArray = (Integer[]) ConvertUtils.convert(orgDutiesArray, Integer.class);
                    for(Integer integer:integerArray){
                        String subjectsHql = "from OrgDuties where deleted_at = null and id = " + integer;
                        OrgDuties orgDuties = orgDutiesDao.findId(subjectsHql, null);//1
                        GQLDuty gqlDuty = DutiesMapper.MAPPER.toOrgDuties(orgDuties);
                        gqlDutys.add(gqlDuty);
                    }
                }
            }
            GQLSchoolSettings gqlGQLSchoolSettings = SchoolSettingsMapper.MAPPER.toSchoolsettings(item);
            gqlGQLSchoolSettings.setDuties(gqlDutys);
            gqlGQLSchoolSettings.setGrades(gqlGrades);
            gqlGQLSchoolSettings.setPeriods(gqlPeriods);
            gqlGQLSchoolSettings.setSubjects(gqlSubjects);
            gqlGQLSchoolSettings.setSchool(gqlSchools);
            gqlGQLSchoolSettings.setCourses(gqlCoursess);
            gqlSchoolSettings.add(gqlGQLSchoolSettings);
        }

        Long total = 0L;
        if (environment.getSelectionSet().contains("total")) {
            total = schoolSettingsDao.getTotalCount(hql);
        }
        return Result.ok().put("data", gqlSchoolSettings).put("total", total);
    }


//    /**
//     * 获取学校设置列表
//     *
//     * @param environment
//     * @return
//     * @throws Exception editor : ths
//     */
//    @Override
//    public Object get(DataFetchingEnvironment environment) throws Exception {
//
//        List<GQLSchoolSettings> gqlGQLSchoolSettings = new ArrayList<>();
//
//        String token = tokenService.getSystemToken();
//        if(token==null) {
//            return  R.NoLogin();
//        }
//        Long schoolId = JwtUtils.getSchoolId(token);
////        int id = Integer.parseInt(environment.getArgument("id").toString());
//        GQLPageParam page = EnvArgsMapper.MAPPER.fromArgs(environment);
//        String hql = "from Schoolsettings where deleted_at = null and school_id = " + schoolId;
//        List<Schoolsettings> list = schoolSettingsDao.find(hql, null, page.getPage(), page.getLimit());
//
//
//        for (Schoolsettings item : list) {
//            GQLSchoolSettings schoolSettings = SchoolSettingsMapper.MAPPER.toSchoolsettings(item);
//            gqlGQLSchoolSettings.add(schoolSettings);
//        }
//
//        Long total = 0L;
//        if (environment.getSelectionSet().contains("total")) {
//            total = schoolSettingsDao.getTotalCount(hql);
//        }
//        return Result.ok().put("data", gqlGQLSchoolSettings).put("total", total);
//    }
}
